package com.xyy.saas.payment.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xyy.saas.payment.cores.enums.BusinessOrderTypeEnum;
import com.xyy.saas.payment.cores.enums.PayModeEnum;
import com.xyy.saas.payment.cores.enums.PaySceneEnum;
import com.xyy.saas.payment.cores.enums.RiskControlBusinessTypeEnum;
import com.xyy.saas.payment.dao.model.PayAccount;
import com.xyy.saas.payment.dao.model.RiskControlPayWhitelist;
import com.xyy.saas.payment.dao.model.RiskControlPayWhitelistQueryParam;
import com.xyy.saas.payment.dao.model.UserInfo;
import com.xyy.saas.payment.manage.cores.api.RiskControlPayWhitelistApi;
import com.xyy.saas.payment.manage.cores.bo.RiskControlPayWhitelistBo;
import com.xyy.saas.payment.manage.cores.enums.BusinessIdTypeEnum;
import com.xyy.saas.payment.manage.cores.enums.ChannelEnum;
import com.xyy.saas.payment.manage.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.manage.cores.vo.ResultPageVo;
import com.xyy.saas.payment.manage.cores.vo.ResultVO;
import com.xyy.saas.payment.manage.cores.vo.RiskControlPayWhitelistVO;
import com.xyy.saas.payment.manage.cores.vo.RiskControlRuleItem;
import com.xyy.saas.payment.pojo.dto.UserDto;
import com.xyy.saas.payment.service.PayAccountService;
import com.xyy.saas.payment.service.PinganLoanService;
import com.xyy.saas.payment.service.RiskControlPayWhitelistService;
import com.xyy.saas.payment.service.UserInfoService;
import com.xyy.saas.payment.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import util.AESUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class RiskControlPayWhitelistApiImpl implements RiskControlPayWhitelistApi {

    @Autowired
    private RiskControlPayWhitelistService riskControlPayWhitelistService;
    @Autowired
    private PayAccountService payAccountService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PinganLoanService pinganLoanService;
    @Override
    public String test(String fileDate) {
       try {
           log.info("fileDate");
           pinganLoanService.downloadLoanHuanKuanFile(fileDate, false);

       } catch (Exception e) {
           log.error("fileDate",e);
       }
        return "success";
    }
    @Override
    public String getContent(String fileName) {
        try {
            log.info("getContent:{}",fileName);
            pinganLoanService.getContent(fileName);


        } catch (Exception e) {
            log.error("getContent:{}",fileName,e);
        }
        return "success";
    }
    @Override
    public ResultVO batchAdd(List<RiskControlPayWhitelistVO> entities) {
        log.info("RiskControlPayWhitelistApiImpl#batchAdd start param:{}", JSONUtils.toJSON(entities));
        ResultVO checkResult = checkRiskControlPayWhitelistParam(entities);
        if(!checkResult.isSuccess()) {
            return checkResult;
        }
        // 当前时间
        Date now = new Date();

        List<RiskControlPayWhitelist> list = new ArrayList<>();
        entities.stream().forEach(item -> {
            if(item.getType() == RiskControlBusinessTypeEnum.MERCHANT.getType()) {
                RiskControlPayWhitelist record = new RiskControlPayWhitelist();
                String accountId = payAccountService.getAccountIdByBusiness(BusinessOrderTypeEnum.EC_POP.getType(), item.getPayerId());
                UserInfo userInfo = userInfoService.queryUserInfoByAccountId(accountId);
                String telNo = userInfo.getTelNo();
                String basicInfo = userInfo.getBasicInfo();
                try {
                    telNo = AESUtil.decrypt(telNo, "c9d40faceff82565386d648158c3f1eb");
                    basicInfo = AESUtil.decrypt(basicInfo, "c9d40faceff82565386d648158c3f1eb");
                    UserDto userDto = JSONUtils.parse2Object(basicInfo, UserDto.class);
                    record.setPayerName(userDto.getName());
                    record.setPayerPhone(telNo);
                } catch (Exception e) {
                    log.error("RiskControlPayWhitelistApiImpl#batchAdd decrypt error. ", e);
                }
                if(StringUtils.isNotBlank(item.getPayerName())) {
                    record.setPayerName(item.getPayerName());
                }
                if(StringUtils.isNotBlank(item.getPayerPhone())) {
                    record.setPayerPhone(item.getPayerPhone());
                }
                record.setBusinessType(item.getBusinessType());
                record.setType(RiskControlBusinessTypeEnum.MERCHANT.getType());
                record.setPayerId(accountId);
                record.setStartTime(item.getStartTime());
                record.setEndTime(item.getEndTime());
                if(!CollectionUtils.isEmpty(item.getChannelRules())) {
                    item.getChannelRules().forEach(i -> i.setWhiteListPayType(item.getWhiteListPayType()));
                    record.setChannelRule(JSONUtils.toJSON(item.getChannelRules()));
                }
                record.setCreateTime(now);
                record.setUpdateTime(now);
                record.setYn(1);
                list.add(record);
            }else {
                RiskControlPayWhitelist record = new RiskControlPayWhitelist();
                record.setBusinessType(item.getBusinessType());
                record.setPayerId(item.getPayerId());
                record.setType(item.getType());
                record.setPayerName(item.getPayerName());
                record.setPayerPhone(item.getPayerPhone());
                record.setStartTime(item.getStartTime());
                record.setEndTime(item.getEndTime());
                record.setChannelRule(JSONUtils.toJSON(item.getChannelRules()));
                record.setCreateTime(now);
                record.setUpdateTime(now);
                record.setYn(1);
                list.add(record);
            }
        });
        int rows = riskControlPayWhitelistService.batchAdd(list);
        return ResultVO.createSuccess(rows);
    }

    private ResultVO checkRiskControlPayWhitelistParam(List<RiskControlPayWhitelistVO> entities) {

        for (RiskControlPayWhitelistVO item : entities) {
            if(item.getType() == RiskControlBusinessTypeEnum.MERCHANT.getType()) {
                String accountId = payAccountService.getAccountIdByBusiness(BusinessOrderTypeEnum.EC_POP.getType(), item.getPayerId());
                if(StringUtils.isBlank(accountId)) {
                    return ResultVO.createError(ResultCodeEnum.USER_NOT_FOUND);
                }
            }
            List<RiskControlRuleItem> rules = item.getChannelRules();
            if(CollectionUtils.isNotEmpty(rules)) {
                // 校验
                for (RiskControlRuleItem rule : rules) {
                    if(!ChannelEnum.contains(rule.getChannel())) {
                        return ResultVO.createError(ResultCodeEnum.PAY_CHANNEL_ERROR);
                    }
                    if(PayModeEnum.getEnum(rule.getPayMode()) == null) {
                        return ResultVO.createError(ResultCodeEnum.PAY_MODE_ERROR);
                    }
                    if(PaySceneEnum.getEnum(rule.getPayScene()) == null) {
                        return ResultVO.createError(ResultCodeEnum.PAY_SCENE_ERROR);
                    }
                }
            }
        }
        return ResultVO.createSuccess();
    }

    @Override
    public ResultPageVo pageListByParam(RiskControlPayWhitelistVO param) {
//        log.info("RiskControlPayWhitelistApiImpl#pageListByParam start param:{}", JSONUtils.toJSON(param));
        if(null == param || param.getPage()==0 || param.getPageSize()==0) {
            return ResultPageVo.createFail(ResultCodeEnum.PARAM_ERROR.getDisplayMsg());
        }
        RiskControlPayWhitelistQueryParam queryParam = new RiskControlPayWhitelistQueryParam();
        queryParam.setBusinessType(param.getBusinessType());
        queryParam.setStartTime(param.getStartTime());
        queryParam.setEndTime(param.getEndTime());
        queryParam.setPage(param.getPage());
        queryParam.setPageSize(param.getPageSize());
        queryParam.setPayerId(param.getPayerId());
        if(null != param.getType()
                && RiskControlBusinessTypeEnum.MERCHANT.getType() == param.getType()
                && StringUtils.isNotBlank(param.getPayerId())) {
            String payAccount = payAccountService.getAccountIdByBusiness(BusinessIdTypeEnum.EC_POP.getType(), param.getPayerId());
            if(StringUtils.isNotBlank(payAccount)) {
                queryParam.setPayerId(payAccount);
            }
        }
        queryParam.setType(param.getType());
        queryParam.setPayerName(param.getPayerName());
        queryParam.setPayerPhone(param.getPayerPhone());
        Long total = riskControlPayWhitelistService.getTotal(queryParam);
        List<RiskControlPayWhitelist> list = riskControlPayWhitelistService.pageListByParam(queryParam);
//        log.info("RiskControlPayWhitelistApiImpl#pageListByParam query result total:{}", total);
        List<RiskControlPayWhitelistBo> result = new ArrayList<>();
        list.stream().forEach(item -> {
            RiskControlPayWhitelistBo tmp = new RiskControlPayWhitelistBo();
            BeanUtils.copyProperties(item, tmp);
            tmp.setType(RiskControlBusinessTypeEnum.getEnum(item.getType()).getDesc());
            List<RiskControlRuleItem> riskControlRuleItems = JSONUtils.parse2List(item.getChannelRule(), RiskControlRuleItem.class);
            if(CollectionUtils.isNotEmpty(riskControlRuleItems)) {
                RiskControlRuleItem riskControlRuleItem = riskControlRuleItems.get(0);
                tmp.setChannelRules(riskControlRuleItems);
                tmp.setWhiteListPayType(riskControlRuleItem.getWhiteListPayType());
            }
            if(RiskControlBusinessTypeEnum.MERCHANT.getType() == item.getType()) {
                PayAccount payAccount = payAccountService.getPayAccountByAccountId(item.getPayerId());
                tmp.setPayerId(payAccount.getBusinessUserId());
            }
            result.add(tmp);
        });
        return ResultPageVo.createSuccess(param.getPage(),param.getPageSize(),total,result);
    }

    @Override
    public ResultVO deleteById(Long id) {
        return ResultVO.createSuccess(riskControlPayWhitelistService.deleteById(id));
    }

}
